package com.hmkj.quartz.queue;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.hmkj.boot.utils.SpringContextUtils;
import com.hmkj.common.utils.JsonUtils;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.api.APIUtils;
import com.hmkj.core.api.chuanglan.response.SmsSendResponse;
import com.hmkj.core.api.sendEmail.SendEmailUtils;
import com.hmkj.core.constant.CacheID;
import com.hmkj.core.constant.MsgType;
import com.hmkj.core.constant.State;
import com.hmkj.core.po.system.NoticeLog;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.system.NoticeLogService;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送消息队列线程
 *
 * @author liweidong
 * @date 2017年03月16日 21:38
 */
@Slf4j
public class MessageQueueThread implements Runnable {


    private RedisService redisService = SpringContextUtils.getBean(RedisService.class);
    private NoticeLogService noticeLogService = SpringContextUtils.getBean(NoticeLogService.class);

    @Override
    public void run() {
        while (true) {
            try {
                if (startQueue()) {
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

//    private boolean startQueue() throws Exception {
//        boolean isFinish = false;
//        try {
//            String jsonString = redisService.pop(CacheID.QUEUE_MESSAGE);
//            if (jsonString == null || jsonString.length() == 0) {
//                return true;
//            }
//            log.info("发送通知信息：" + jsonString);
//            NoticeLog notice = (NoticeLog) JsonUtils.toObject(jsonString, NoticeLog.class);
//            log.info(notice.toString());
//            if (notice.getType() == MsgType.EMAIL) {
//                log.info("执行发送邮件");
//                sendEmail(notice);
//            } else if (notice.getType() == MsgType.SMS) {
////                sendSmsByChuangLan(notice);
////                sendSmsByZhuTong(notice);
//                sendSmsByAliyun(notice);
//            } else if (notice.getType() == MsgType.LETTER) {
//                sendLetter(notice);
//            }
//        } catch (Exception e) {
//            log.error("执行短信队列失败：" + e.getMessage());
//            e.printStackTrace();
//        }
//        return isFinish;
//    }

    private boolean startQueue() throws Exception {
        boolean isFinish = false;
        try {
            String jsonString = redisService.pop(CacheID.QUEUE_MESSAGE_ALI);
            if (jsonString == null || jsonString.length() == 0) {
                return true;
            }
            log.info("发送通知信息：" + jsonString);
            Map<String,Object> param = (Map<String, Object>) JsonUtils.toObject(jsonString,Map.class);
            log.info(param.toString());
            sendSmsByAliyun(param);
        } catch (Exception e) {
            log.error("执行短信队列失败：" + e.getMessage());
            e.printStackTrace();
        }
        return isFinish;
    }

    /**
     * 发送邮件消息
     *
     * @param notice
     */
    private void sendEmail(NoticeLog notice) throws Exception {
        log.info("开始发送邮件");
        SendEmailUtils.sendEmail(notice.getTitle(), notice.getContent(), notice.getReceiveAddress());
        noticeLogService.insert(notice);
        log.info("发送了消息到：" + notice.getReceiveAddress());
    }


    /**
     * 发送短信消息(助通)
     *
     * @param notice
     */
    private void sendSmsByZhuTong(NoticeLog notice) {
        String mobile = notice.getReceiveAddress();
        String content = StringUtils.isNull(notice.getContent());
        String result = "";
        //发送短信
        try {
            result = APIUtils.sendSmsZT(mobile, content);
            String[] objStr = result.split(",");
            if (objStr[0].equals("1")) {
                notice.setStatus(State.YES);
                notice.setResult("通过助通发送短信成功");
            } else {
                notice.setStatus(State.NO);
                notice.setResult("通过助通发送短信失败，异常消息：" + objStr[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            notice.setStatus(State.NO);
            notice.setResult("通过助通发送短信失败:" + e.getMessage());
        }
        notice.setRemark(result);
        notice.setCreateTime(new Date());
        noticeLogService.insert(notice);
    }

    /**
     * 发送短信消息(创蓝)
     *
     * @param notice
     */
    private void sendSmsByChuangLan(NoticeLog notice) {
        String mobile = notice.getReceiveAddress();
        String content = StringUtils.isNull(notice.getContent());
        String result = "";
        //发送短信
        try {
            result = APIUtils.sendSmsCL(mobile, content);

            SmsSendResponse smsSingleResponse = JSON.parseObject(result, SmsSendResponse.class);
            if ("0".equals(smsSingleResponse.getCode())) {
                notice.setStatus(State.YES);
                notice.setResult("通过创蓝发送短信成功");
            } else {
                notice.setStatus(State.YES);
                notice.setResult("通过创蓝发送短信失败，异常消息：" + smsSingleResponse.getErrorMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            notice.setStatus(State.NO);
            notice.setResult("通过创蓝发送短信失败:" + e.getMessage());
        }
        notice.setRemark(result);
        notice.setCreateTime(new Date());
        noticeLogService.insert(notice);
    }


    /**
     * 发送短信消息(ALi)
     *
     * @param params
     */
    private void sendSmsByAliyun(Map<String,Object> params) throws Exception {
        String template = (String)params.get("template");
        NoticeLog notice = new NoticeLog();
        notice.setNid(template);
        notice.setType(MsgType.SMS);
        notice.setTitle((String) params.get("title"));
        notice.setUserId((Integer) params.get("userId"));
        notice.setReceiveAddress((String) params.get("mobile"));
        notice.setContent("发送短信");
        SendSmsResponse response = null;
        //发送短信
        try {
            response = APIUtils.sendSmsAL(params);
            if(null != response && response.getCode() != null && response.getCode().equals("OK")) {
                notice.setStatus(State.YES);
                notice.setResult("通过阿里云发送短信成功");
            }else{
                notice.setStatus(State.NO);
                notice.setResult("通过阿里云发送短信失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            notice.setStatus(State.NO);
            notice.setResult("通过助通发送短信失败:" + e.getMessage());
        }
        notice.setRemark(response.getMessage());
        notice.setCreateTime(new Date());
        noticeLogService.insert(notice);
    }


    /**
     * 发送站内信消息
     *
     * @param noticeLog
     */
    private void sendLetter(NoticeLog noticeLog) {
        noticeLogService.insert(noticeLog);
    }
}
